package com.dragon.english_practice_back.config;



import com.dragon.english_practice_back.filter.TokenFilter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfigurationSource;

@Slf4j
@Configuration
@EnableWebSecurity//开启Spring Security的功能
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig {
    @Resource
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenFilter tokenFilter;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    AccessDeniedHandler accessDeniedHandler;

    @Autowired
    CorsConfigurationSource corsConfigurationSource;
    @Bean
    ProviderManager authenticationManager() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        return new ProviderManager(daoAuthenticationProvider);
    }

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                //关闭默认登录
                .formLogin(AbstractHttpConfigurer::disable)
                //关闭csrf
                .csrf(AbstractHttpConfigurer::disable)
                //不使用session存储信息
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //设置匿名
                .authorizeHttpRequests(customize -> customize
                        .requestMatchers("/hello").permitAll()
                        .requestMatchers("/start/login").permitAll()
                        .requestMatchers("/start/register").permitAll()
                        .requestMatchers("/start/checkEmailIsAvailable").permitAll()
                        .requestMatchers("/ai/**").permitAll()
                        .requestMatchers("/translate/assistantSuggestion").permitAll()
                        .requestMatchers("/doc.html/**").permitAll()
                        .requestMatchers("/v3/api-docs/**").permitAll()
                        .requestMatchers("/webjars/**").permitAll()
                        .anyRequest().authenticated())

                //设置错误处理
                .exceptionHandling(customize -> customize
                        //身份验证失败
                        .authenticationEntryPoint(authenticationEntryPoint)
                        //权限验证失败
                        .accessDeniedHandler(accessDeniedHandler))

                //设置跨域
                .cors(customizer -> customizer.configurationSource(corsConfigurationSource))

                //将tokenFilter放置在UPAFilter前面
                .addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }

    /**
     * 指定加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        // 使用BCrypt加密密码
        return new BCryptPasswordEncoder();
    }
}